<template>
  <div class="comment-box">
    <div class="comment-box_title" @click="handleClick">
      <span>{{ inputTitle }}</span>
      <i class="iconfont icon-close" v-show="isShowInput" @click.stop="closeInput"></i>
    </div>
    <div class="comment-box_input" v-show="isShowInput">
      <textarea type="text" style="resize:none;" placeholder="请输入评论" v-model="commentValue" />
      <div class="input-options">
        <i class="iconfont icon-required"></i
        ><input type="text" placeholder="github用户名" v-model="github" />
        <input type="text" placeholder="博客地址" v-model="blog" />
        <button :class="btnCls" @click="publishComment" :disabled="!(commentValue && github)">
          发表评论
        </button>
      </div>
    </div>
    <div class="comment-box_list" v-if="commentList.length">
      <div class="title">全部评论({{ commentList.length }})</div>
      <div class="comment-box_list--items" v-for="item in commentList" :key="item.cid">
        <img :src="item.avatar" alt="" />
        <div class="content">
          <p>{{ item.name }}</p>
          <p>
            <span>{{ item.createTime | timestampToTime }}</span>
          </p>
          <p>{{ item.text }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '../../../api/comment'
export default {
  data() {
    return {
      isShowInput: false,
      github: '',
      blog: '',
      commentValue: '',
      commentList: []
    }
  },
  methods: {
    // 发表评论
    async publishComment() {
      const params = {
        id: this.$route.params.id,
        text: this.commentValue,
        name: this.github,
        url: this.blog
      }
      try {
        const res = await api.addComment(params)
        if (res.code === 200) {
          this.$Message.success(res.message)
          this.isShowInput = false
          this.getCommentLists()
        }
      } catch (err) {
        console.log(err)
      }
    },

    // 获取评论列表
    async getCommentLists() {
      const params = {
        id: this.$route.params.id
      }
      try {
        const res = await api.getCommentList(params)
        if (res.code === 200) {
          this.commentList = res.data
        }
      } catch (err) {
        console.log(err)
      }
    },

    handleClick() {
      this.isShowInput = true
    },

    closeInput() {
      this.isShowInput = false
    }
  },
  computed: {
    btnCls: function() {
      return {
        active: this.commentValue && this.github
      }
    },
    inputTitle: function() {
      return this.isShowInput ? '发表评论' : '万丈高楼平地起,评论搭楼还差你'
    }
  },
  mounted() {
    this.getCommentLists()
  }
}
</script>
